"""
@Project:${2108a 人工智能}
@File:main.py
@Author:周家昌
@Date:20:46
"""
from flask import Flask, render_template, jsonify
from flask import request
from flask import make_response
from flask import redirect
app = Flask(__name__)

UserList = []


@app.route('/', methods=['GET', 'POST'])
def register():
    if request.method=="POST":
        # 从前端表单输入框中获取数据
        username = request.form.get('username')
        pwd = request.form.get('pwd')
        if username not in UserList:
            UserList.append({'username':username,'pwd':pwd})
            print('字典的数据为：',UserList)
            return redirect('/login/')
        else:
            resp = make_response(' 用户名已存在 ！ ')
            # 重定向
            return resp

    return render_template('register.html')



@app.route('/login/',methods=['POST','GET'])
def login():
    if request.method == "POST":
        name = request.form.get('username')
        pwd = request.form.get('pwd')
        print('当前的用户名和密码为：', name, pwd)
        if name not in [i['username'] for i in UserList]:
            resp = make_response(' 用户名不存在 ！ ')
            # 重定向
            return resp
        else:
            for i in UserList:
                if i['username']==name and i['pwd']==pwd:

                    return redirect('/index/')
            else:
                resp = make_response('账号或密码错误！')
                # 重定向
                return resp


    return render_template('login.html')

@app.route('/index/',methods=['POST','GET'])
def index():
    if request.method=='GET':
        # 返回json数据
        print('json格式',jsonify(UserList))
        for i in UserList:
            name1 = i['username']
        return render_template('index.html',name=name1)

    if request.method == "POST":
        name = request.form.get('username')

        print('当前的用户名和密码为：', name)
        try:
            for i in UserList:
                i['username'] = name
        except Exception as e:
            return e


    return ('修改成功%s'%UserList)


@app.route('/image/',methods=['POST','GET'])

def image():
    file = request.files.get('name')
    image_name = file.filename
    resp = make_response(image_name)
    resp.headers['Content-Type'] = 'image/png'
    print(resp)

    return resp


if __name__ == '__main__':
    app.run(debug=True)